package main

import (
	"context"
	"errors"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"

	"google.golang.org/grpc"

	"gitee.com/keion8620/go-zero-lean/traning/2-6/user"
)

type UserInfo struct {
	Id    string `json:"id"`
	Name  string `json:"name"`
	Phone string `json:"phone"`
}

var userMap = map[string]UserInfo{
	"1": {
		Id:    "1",
		Name:  "test1",
		Phone: "16431346345",
	},
	"2": {
		Id:    "2",
		Name:  "test2",
		Phone: "134546431312",
	},
	"3": {
		Id:    "3",
		Name:  "test3",
		Phone: "5497465354652",
	},
}

type UserServer struct {
}

func (u *UserServer) GetUserInfo(ctx context.Context, req *user.GetUserReq) (*user.GetUserResp, error) {
	if u, ok := userMap[req.Id]; ok {
		return &user.GetUserResp{
			Id:    u.Id,
			Name:  u.Name,
			Phone: u.Phone,
		}, nil
	}
	return nil, errors.New("用户不存在")
}

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal("监听8080端口失败", err)
	}
	defer listener.Close()

	grpcServer := grpc.NewServer()
	grpcServer.RegisterService(&user.UserService_ServiceDesc, new(UserServer))

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		log.Println("gRPC服务器启动, 监听端口 :8080")
		if err := grpcServer.Serve(listener); err != nil {
			log.Println("启动gRPC服务器失败", err)
		}
	}()
	<-sigChan
	log.Println("关闭gRPC服务器")
	grpcServer.GracefulStop()
	log.Println("gRPC服务器已关闭")
}
